<template>
  <div class="interaction">
    <div class="live">
      <div class="live-header">
        <h2>实时课堂</h2>
      </div>
      <div class="father">
          <barrages id="danmu" :chatMessageList="chatMessageList"></barrages>
          <video id="videoElement" controls muted>
          </video>
          <div v-if="redPointVisible" class="little-redpoint"></div>
      </div>
      <div class="btn-area">
        <a-space>
          <!-- <a-button @click="deleteAll" type="primary">开启本地</a-button> pauseStatus -->
          <a-button @click="startRecord" type="primary">开始录制</a-button>
          <a-button v-if="!pauseStatus" @click="pauseRecord" type="primary"
            >暂停录制</a-button
          >
          <a-button v-if="pauseStatus" @click="continueRecord" type="primary"
            >继续录制</a-button
          >
          <a-button @click="stopRecord" type="danger">结束录制</a-button>
          <a-button @click="closeRoom" type="danger">结束授课</a-button>
        </a-space>
      </div>
    </div>
    <div class="onlineInfo">
      <div class="onlineInfo-header">
        <div class="onlineInfo-filter" :class="{active: peopleIsActive}" @click="people">成员列表</div>
        <div class="onlineInfo-chating" :class="{active: chatIsActive}" @click="chat" >聊天</div>
        <div class="onlineInfo-arrow">当前{{ currentAudience }}人在线</div>
      </div>
      <div class="chat" v-if="!visible">
        <div class="chats">
          <label class="contentlabel">聊天内容</label>
          <div class="chatRoom" id="chatScroll">
          <div
          class="chatContent"
          v-for="(message, index) in chatMessageList"
          :key="index">
          <div>
          <p class="">{{ message.userName }}：{{ message.chatMessage }}</p>
          </div>
          </div>
          </div>
        </div>
       <div class="chating">
            <input type="text" v-model="chatMessage"  placeholder=" 请输入聊天内容"/>
            &nbsp;
            <button @click="sendMessage(chatMessage)">发送</button>
          </div>
      </div>
      <div class="onlineInfo-body" v-if="visible">
        <div class="onlineInfo-body-title">
          <div class="onlineInfo-body-title-left">姓名</div>
          <div class="onlineInfo-body-title-center">进入时间</div>
          <div class="onlineInfo-body-title-right">是否签到</div>
        </div>
        <div class="onlineInfo-body-list">
          <ul class="onlineInfo-body-ul">
            <li
              class="onlineInfo-body-li"
              v-for="item in audienceList"
              :key="item.studentName"
            >
              <span class="onlineInfo-body-li-name">
                {{ item.studentName
                }}<b v-if="item.role === 'teacher'">🧑🏻‍🏫</b></span
              >
              <span class="onlineInfo-body-li-time">{{
                item.enterTime | timeFormatter
              }}</span>
              <span class="onlineInfo-body-li-flag">
                <b v-if="item.role !== 'teacher'">🐾</b>
                <b v-else>🔥</b></span
              >
            </li>
          </ul>
        </div>
      </div>
      <!-- {{ item.signStatus }}-->
    </div>
    <!-- <a-modal v-model="livingVisible" title="请选择授课模式" @ok="startCourse">
      <a-select
        style="width: 100%"
        :default-value="livingMode"
        @change="updateLivingMode"
      >
        <a-select-option value="living"> 直播 </a-select-option>
        <a-select-option value="record"> 录制 </a-select-option>
        <a-select-option value="RtmpAddRecord"> 录播 </a-select-option>
      </a-select>
    </a-modal> -->
  </div>
</template>

<script>
import moment from "moment";
import axios from "@/utils/axios";
import * as socket from "@/utils/socket";
import { mapState } from "vuex";
import flvjs from "flv.js";
import barrages from "@/pages/student/course/class/bulletScreen.vue";

export default {
  components:{
    barrages
  },
  data() {
    return {
      // 计时器
      RecordcounterStatus: false,
      count: 0,
      Recordcount: "",
      // 聊天室
      chatMessage: "",
      pauseStatus: false, //是否暂停
      deviceIP: "",
      room_number: "",
      client: null,
      localStream: null,
      roomDisabled: false,
      liveDisabled: true,
      closeDiabled: true,
      pagination: {
        pageSize: 6,
      },
      livingVisible: false,
      signedDataArray: [],
      questionDataArray: [],
      voteDataArray: [],
      testDataArray: [],
      fileDataArray: [],
      visible: true,
      redPointVisible:false,
      peopleIsActive:false, //点击成员列表的时候成员变量一直有颜色
      chatIsActive:false,
    };
  },
  computed: {
    ...mapState({
      // livingMode: (state) => state.teacher.livingMode,
      chatMessageList: (state) => state.teacher.chatMessage,
      chatMessageListT: (state) => state.student.chatMessage,
      uid: (state) => state.public.uid,
      oid: (state) => state.public.oid,
      userName: (state) => state.public.userName,
      precourse: (state) => state.teacher.precourse,
      prepareLessonStatus: (state) => state.teacher.prepareLessonStatus,
      curActivityID: (state) => state.teacher.curActivityID,
      curclassName: (state) => state.teacher.curclassName,
      curclassId: (state) => state.teacher.curclassId,
      teacherId: (state) => state.public.studentId,
      teacherName: (state) => state.public.userName,
      onlineList: (state) => state.teacher.onlineList,
      realStudents: (state) => state.teacher.curRealStudents,
      signList: (state) => state.teacher.signList,
      raceList: (state) => state.teacher.raceList,
      randomSignList: (state) => state.teacher.randomList,
      randomStudents: (state) => state.teacher.randomStudents,
      questionsDataList: (state) => state.teacher.ask_answer,
      voteDataList: (state) => state.teacher.voteAnswerList,
      voteShowList: (state) => state.teacher.voteShowList,
      testDataList: (state) => state.teacher.testAnswerList,
      fileDataList: (state) => state.teacher.fileAnswerList,
    }),
    audienceList() {
      let audienceList = this.onlineList.map((item) => {
        item.signStatus = "否";
        this.signList.forEach((element) => {
          if (element.studentName == item.studentName) {
            item.signStatus = "是";
          }
        });
        return {
          signStatus: item.signStatus,
          studentName: item.studentName,
          enterTime: item.enterTime,
          role: item.role,
          studentId: item.studentId,
        };
      });
      return audienceList;
    },
    lessonId() {
      return this.$route.query.lessonId;
    },
    currentAudience() {
      return this.audienceList.length;
    },
  },
  filters: {
    timeFormatter(value) {
      console.log(value);
      if (value == undefined) {
        return;
      }
      return value.trim().split(" ")[1];
    },
  },
  async created() {
    //开始推流
    await this.startRtmp();
    //开始拉流
    this.pullVideoStream();
  },
  mounted() {
    this.$store.commit("teacher/clearOnlineList");
    this.$store.dispatch("teacher/getOnlineStudents", this.lessonId);
    // 2）当前课程活动写入课程事件数据
    // 判断 无备课课程
    if (this.prepareLessonStatus) {
      console.log("comesss");
      return;
    }
    let phaseArrData = [];
    console.log("当前课程活动写入课程事件数据");
    if (!this.precourse.nodes) {
      this.precourse.nodes = [];
    }
    this.precourse.nodes.forEach((item, index) => {
      let objData = {
        phase_time: parseInt(item.time.slice(0, 2)),
        phase_type: item.tag,
        phase_index: index,
      };
      phaseArrData.push(objData);
    });
    console.log(phaseArrData);
    const payload = {
      activity_id: this.curActivityID,
      phases: phaseArrData,
      lessonId: this.lessonId,
      courseHourName: this.$route.query.name,
    };
    console.log("更新教学活动测试");
    axios
      .patch("pc/v1/activities/" + this.curActivityID, payload)
      .then(({ data }) => {
        console.log("更新教学活动成功");
      })
      .catch((err) => {
        console.error(err);
        this.$message.error("更新活动失败");
      });
  },
  methods: {
    async sendMessage(chatMessage) {
      this.chatMessage = "";
      this.chatMessageList.push({
        userName: this.userName,
        chatMessage: chatMessage
      })
      console.log(this.chatMessageList);
      // 发送消息
      socket.sendEvent("joinRoom", {
        actionType: "chat",
        role: "teacher",
        roomId: this.lessonId,
        data: {
          userName: this.userName,
          chatMessage: chatMessage,
        },
      });
     await this.$forceUpdate();   
     var div = document.getElementById('chatScroll');
     div.scrollTop = div.scrollHeight;
     //  document.getElementsByClassName("chatContent")[this.chatMessageList.length-1].scrollIntoView();
     //  var now = new Date();
     // div.innerHTML = div.innerHTML + 'time_' + now.getTime() + '<br />';
    },
    Recordcounter() {
      // 录播计时，超过50分自动关闭并上传!
      this.count++;
      console.log(
        "🚀 ~ file: Live.vue ~ line 213 ~ Recordcounter ~ this.count",
        this.count
      );
      if (!this.RecordcounterStatus) {
        this.count = 3000;
        this.count = 0;
        return;
      }
      if (this.count >= 60 * 50) {
        this.stopRecord();
        this.count = 0;
        return;
      }
      // document.display1.box1.value = count;
      this.Recordcount = window.setTimeout(() => {
        this.Recordcounter();
      }, 1000);
    },
    async startRecord() {
      try {
        
        // 开始录像
        let url = "/pc/v1/devices/record/" + this.$route.query.room_id;
        let { data } = await axios.get(url);
        // this.updateLivingMode("record");
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        this.$message.info("已开始录制");
        // 开始计时
        this.RecordcounterStatus = true;
        this.Recordcounter();
        this.redPointVisible=true;
        let p=document.querySelector(".little-redpoint");
        p.className="little-redpoint";
      } catch (err) {
        console.log(err);
        this.$message.error("设备连接失败，请重试");
      }
    },
    async continueRecord() {
      try {
        // 继续录像
        let url = "/pc/v1/devices/continueRecord/" + this.$route.query.room_id;
        let { data } = await axios.get(url);
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        this.$message.info("已继续直播");
        this.pauseStatus = false;
        this.redPointVisible=true;
        let p=document.querySelector(".little-redpoint");
        p.className="little-redpoint";
      } catch (err) {
        console.log(err);
        this.$message.error("设备连接失败，请重试");
      }
    },
    async pauseRecord() {
      try {
        // 暂停录像
        let url = "/pc/v1/devices/pauseRecord/" + this.$route.query.room_id;
        let { data } = await axios.get(url);
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        this.$message.info("录制暂停成功");
        this.pauseStatus = true;
        this.redPointVisible=true;
        let p=document.querySelector(".little-redpoint");
        p.className="little-redpoint-display";
      } catch (err) {
        console.log(err);
        this.$message.error("设备连接失败，请重试");
      }
    },
    async stopRecord() {
      try {
        // 停止录制
        this.redPointVisible=false;
        let url = "/pc/v1/devices/stopRecord/" + this.$route.query.room_id;
        let requestData = {
          authorId: this.uid,
          lessonId: this.$route.query.lessonId,
          oid: this.oid,
          date: moment().format("LLL"),
          teacherName: this.userName,
          className: this.curclassName,
          courseName: this.$route.query.courseName,
        };
        let { data } = await axios.post(url, requestData);
        if (data.status == "fail") {
          this.$message.error(data.message);
          console.log("come");
          this.count = 3000;
          console.log(
            "🚀 ~ file: Live.vue ~ line 296 ~ stopRecord ~ this.count",
            this.Recordcount
          );

          return;
        }
        // 获取下载路径
        this.$message.info("上传成功");
        // 停止计时
        this.RecordcounterStatus = false;
        // this.count = 3000;
      } catch (err) {
        console.log(err);
        this.$message.error("上传失败");
      }
    },
    async startRtmp() {
      try {
        let url = "/pc/v1/devices/startRtmp/" + this.$route.query.room_id;
        let { data } = await axios.get(url);
        // 记录IP
        this.deviceIP = data.device.deviceIP;
        // console.log("🚀 ~ file: Live.vue ~ line 216 ~ startRtmp ~ device", device)
        if (data.status == "fail") {
          this.$message.error(data.message);
          //d4096e50-8893-11eb-ae68-3563477c4edf
          return;
        }
        this.$message.info("已开始直播");
        // 开始拉流
        this.pullVideoStream();
      } catch (err) {
        console.log(err);
        this.$message.error("设备连接失败，请重试！");
      }
    },
    async stopRtmp() {
      try {
        // 停止直播
        let url = "/pc/v1/devices/stopRtmp/" + this.$route.query.room_id;
        let requestData = {
          authorId: this.uid,
          lessonId: this.$route.query.lessonId,
          oid: this.oid,
        };
        let { data } = await axios.post(url, requestData);
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        console.log(
          "🚀 ~ file: Live.vue ~ line 222 ~ completeLiving ~ data",
          data
        );
        this.$message.info("直播停止成功");
      } catch (err) {
        console.log(err);
        this.$message.error("上传失败");
      }
    },
    async RtmpAddRecord() {
      try {
        let url = "/pc/v1/devices/RtmpAddRecord/" + this.$route.query.room_id;
        let { data } = await axios.get(url);
        console.log(
          "🚀 ~ file: Live.vue ~ line 290 ~ RtmpAddRecord ~ data",
          data
        );
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        this.deviceIP = data.device.deviceIP;
        // 拉流
        this.pullVideoStream();
        this.$message.info("开始录播");
      } catch (err) {
        console.log(err);
        this.$message.error("设备连接失败,请重试");
      }
    },
    async closeRtmpAddRecord() {
      try {
        // 停止直播
        let url =
          "/pc/v1/devices/closeRtmpAddRecord/" + this.$route.query.room_id;
        let requestData = {
          authorId: this.uid,
          lessonId: this.$route.query.lessonId,
          oid: this.oid,
        };
        let { data } = await axios.post(url, requestData);
        if (data.status == "fail") {
          this.$message.error(data.message);
          return;
        }
        console.log(
          "🚀 ~ file: Live.vue ~ line 222 ~ completeLiving ~ data",
          data
        );
        this.$message.info("上传成功");
      } catch (err) {
        console.log(err);
        this.$message.error("上传失败");
      }
    },
    pullVideoStream() {
      if (flvjs.isSupported()) {
        var videoElement = document.getElementById("videoElement");
        let roomNumber = this.$route.query.roomNumber;
        var flvPlayer = flvjs.createPlayer({
          type: "flv",
          isLive: true,
          hasVideo: true,
          hasAudio: true,
          url: `${this.$URLS.liveServer}/live?port=1935&app=live&stream=${roomNumber}`,
        });
        this.player = flvPlayer;
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        // play | pause
        flvPlayer.play();
      } else {
        alert(
          `您的浏览器不支持视频流播放\n建议使用 Chrome、FireFox 等主流浏览器`
        );
      }
    },
    async closeLiveRoom() {
      try {
        const leaveResult = await this.client.leave();
        console.log(leaveResult);
        this.localStream.close();
        this.localStream = null;
        console.log("退房成功 ");
        // 修改教室状态为using
        this.$store.dispatch("teacher/updateRoomStatus", {
          room_id: this.$route.query.room_id,
          status: "using",
          lessonId: this.$route.query.lessonId,
        });
        // 退房成功，可再次调用client.join重新进房开启新的通话。
      } catch (error) {
        console.error("退房失败 " + error);
        // 错误不可恢复，需要刷新页面。
      }
    },
    async closeRoom() {
      try {
        // 检测录制是否关闭
        if (this.count != 0 && this.count < 3000) {
          this.$message.error("请先停止录制");
          return;
        }
        if (this.prepareLessonStatus) {
          console.log("comesss555555555");
          // 2）更改房间使用状态 清空redis
          this.$store.dispatch("teacher/clearRoomMembers", {
            channelId: this.$route.query.lessonId,
          });
          await this.$store.dispatch("teacher/updateRoomStatus", {
            room_id: this.$route.query.room_id,
            status: "avaliable",
            lessonId: null,
          });
          // 3) 页面跳转返回主页 TODO
          socket.sendEvent("joinRoom", {
            actionType: "leave",
            role: "teacher",
            roomId: this.lessonId,
            data: { studentId: this.teacherId },
          });
          this.$store.commit("teacher/clearActivity");
          // 结束直播
          this.stopRtmp();
          // 初始化直播状态
          // this.updateLivingMode("living");
          // 跳转页面
          this.$router.push({ name: "teacher_index" });
          return;
        }
        // 1）保存本次课教学活动 TODO
        // 本次课活动列表
        let payload = {};
        //添加必要信息
        payload = {
          ...payload,
          total_number: this.realStudents.length,
          real_number: this.currentAudience,
          end_time: moment().format("YYYY-MM-DD HH:mm:ss"),
          className: this.curclassName,
        };
        this.precourse.nodes.forEach((node) => {
          if (node.tag === "Race") {
            this.saveRaceData(payload);
          }
          if (node.tag === "randomSign") {
            this.saveRandomSignData(payload);
          }
          if (node.tag === "Ask") {
            this.saveQuestionData();
            // 先赋值questionData 再清空questionDataArray
            [...payload.question_data] = this.questionDataArray;
            this.questionDataArray.length = 0;
          }
          if (node.tag === "Sign") {
            this.saveSignData();
            [...payload.sign_data] = this.signedDataArray;
            this.signedDataArray.length = 0;
          }
          if (node.tag === "Vote") {
            this.saveVoteData();
            [...payload.vote_data] = this.voteDataArray;
            this.voteDataArray.length = 0;
          }
          if (node.tag === "Test") {
            this.saveTestData();
            [...payload.test_data] = this.testDataArray;
            this.testDataArray.length = 0;
          }
          if (node.tag === "File") {
            this.saveFileData();
            [...payload.file_data] = this.fileDataArray;
            this.fileDataArray.length = 0;
          }
        });
        await this.$store.dispatch("teacher/saveActivityMessage", {
          curActivityID: this.curActivityID,
          payload,
        });
        // 2）更改房间使用状态 清空redis
        this.$store.dispatch("teacher/clearRoomMembers", {
          channelId: this.$route.query.lessonId,
        });
        await this.$store.dispatch("teacher/updateRoomStatus", {
          room_id: this.$route.query.room_id,
          status: "avaliable",
          lessonId: null,
        });

        // 3) 页面跳转返回主页 TODO
        socket.sendEvent("joinRoom", {
          actionType: "leave",
          role: "teacher",
          roomId: this.lessonId,
          data: { studentId: this.teacherId },
        });
        this.$store.commit("teacher/clearActivity");
        // 结束直播
        this.stopRtmp();
        // 初始化直播状态
        // this.updateLivingMode("living");
        // 跳转页面
        this.$router.push({ name: "teacher_index" });
      } catch (err) {
        console.log(err);
        this.$message.error("信息保存失败");
      }
    },
    saveRandomSignData(payload) {
      if (!payload.randomSign_data) payload.randomSign_data = [];
      this.randomStudents.forEach((student) => {
        student.signStatus = "未签到";
        this.randomSignList.forEach((randomData) => {
          if (student.studentName === randomData.studentName) {
            student.signStatus = "已签到";
          }
        });
      });
      payload.randomSign_data = this.randomStudents;
    },
    saveRaceData(payload) {
      if (!payload.race_data) payload.race_data = [];
      if (this.raceList.length === 0) {
        return;
      }
      let race_students = [];

      let question = {
        title: this.raceList[0].question.content,
        options: this.raceList[0].question.options,
        question_type: this.raceList[0].question.type,
        right_answer: this.raceList[0].question.right_answer,
      };

      this.realStudents.forEach((real) => {
        let questionStatus = {};
        let flag = false;
        this.raceList.forEach((online) => {
          if (real.user_id == online.studentID) {
            questionStatus = {
              studentId: online.studentID,
              studentName: online.studentName,
              answerSelection: online.answerSelection,
              answerResult: online.answerResult,
              joinFlag: true,
            };
            flag = true;
            race_students.push(questionStatus);
          }
        });
        if (flag == false) {
          questionStatus = {
            studentId: real.user_id,
            studentName: real.name,
            answerSelection: "",
            answerResult: false,
            joinFlag: false,
          };
          race_students.push(questionStatus);
        }
      });
      let raceData = {
        total_number: this.realStudents.length,
        real_number: race_students.length,
        class_name: this.curclassName,
        class_id: this.curclassId,
        question,
        studentAnswerList: race_students,
      };
      payload.race_data.push(raceData);
    },
    saveSignData() {
      // **************保存签到数据
      console.log("保存签到数据");
      let finalList = [];
      this.realStudents.forEach((real) => {
        let finalStatus = {};
        let flag = false;
        this.audienceList.forEach((online) => {
          if (real.user_id == online.studentId && online.role != "teacher") {
            finalStatus = {
              _id: real._id,
              studentId: online.studentId,
              studentName: online.studentName,
              enterTime: online.enterTime,
              signStatus: online.signStatus,
              joinFlag: true,
            };
            flag = true;
            finalList.push(finalStatus);
          }
        });
        if (flag == false) {
          finalStatus = {
            _id: real._id,
            studentId: real.user_id,
            studentName: real.name,
            enterTime: "",
            signStatus: "",
            joinFlag: false,
          };
          finalList.push(finalStatus);
        }
      });
      // let signedDataArray = [];
      let sData = {
        total_number: this.realStudents.length,
        real_number: this.audienceList.length - 1,
        class_name: this.curclassName,
        class_id: this.curclassId,
        class_list: finalList,
      };
      this.signedDataArray.push(sData);
    },
    saveQuestionData() {
      // **************保存提问数据
      let questionAnswersData = [];
      let join_student_count = 0;
      // 保存题目信息
      if (!this.questionsDataList.length) {
        return;
      }
      let question = {
        title: this.questionsDataList[0].question.content,
        options: this.questionsDataList[0].question.options,
        question_type: this.questionsDataList[0].question.type,
        right_answer: this.questionsDataList[0].question.right_answer,
      };
      this.realStudents.forEach((real) => {
        let questionStatus = {};
        let flag = false;
        this.questionsDataList.forEach((online) => {
          if (real.user_id == online.studentId && online.role != "teacher") {
            questionStatus = {
              questionId: online.id,
              studentId: online.studentId,
              studentName: online.studentName,
              answerSelection: online.answerSelection,
              answerTime: online.answerTime,
              answerResult: online.answerResult,
              joinFlag: true,
            };
            join_student_count++;
            flag = true;
            questionAnswersData.push(questionStatus);
          }
        });
        if (flag == false) {
          questionStatus = {
            questionId: "",
            studentId: real.user_id,
            studentName: real.name,
            answerSelection: "",
            answerTime: "",
            answerResult: false,
            joinFlag: false,
          };
          questionAnswersData.push(questionStatus);
        }
      });

      let questionData = {
        total_number: this.realStudents.length,
        real_number: join_student_count,
        class_name: this.curclassName,
        class_id: this.curclassId,
        question,
        studentAnswerList: questionAnswersData,
      };
      this.questionDataArray.push(questionData);
    },
    chat(){
      this.visible = false;
      this.peopleIsActive=false;
      this.chatIsActive=true;
    },
    people(){
      this.visible = true;
      this.peopleIsActive=true;
      this.chatIsActive=false;
    },
    saveVoteData() {
      // *******保存投票数据 voteShowList
      let NumToEng = ["A", "B", "C", "D", "E", "F", "G"];
      let voteAnswersData = [];
      let join_student_count = 0;
      this.voteDataList.forEach((voteData) => {
        voteData.question.forEach((questionItem, index) => {
          let studentAnswerList = [];
          this.realStudents.forEach((real) => {
            let voteStatus = {};
            let flag = false;

            this.voteDataList.forEach((online) => {
              if (real.user_id == online.studentId) {
                voteStatus = {
                  studentId: online.studentId,
                  studentName: online.studentName,
                  joinFlag: true,
                  answerSelection:
                    NumToEng[online.result_list[index].voteSelection],
                };
                join_student_count++;
                flag = true;
                studentAnswerList.push(voteStatus);
              }
            });
            if (flag == false) {
              voteStatus = {
                studentId: real.user_id,
                studentName: real.name,
                joinFlag: false,
                answerSelection: "",
              };
              studentAnswerList.push(voteStatus);
            }
          });
          //
          voteAnswersData.push({
            studentAnswerList,
            question: {
              title: questionItem.content,
              options: questionItem.options,
              question_type: questionItem.type,
            },
          });
        });
      });

      let voteData = {
        total_number: this.realStudents.length,
        real_number: join_student_count,
        class_name: this.curclassName,
        class_id: this.curclassId,
        record: voteAnswersData,
      };
      this.voteDataArray.push(voteData);
    },
    saveTestData() {
      // **************保存随堂测试数据
      let NumToEng = ["A", "B", "C", "D", "E", "F", "G"];
      let testAnswersData = [];
      let join_student_count = 0;
      this.testDataList.forEach((testData) => {
        testData.question.forEach((questionItem, index) => {
          let studentAnswerList = [];
          this.realStudents.forEach((real) => {
            let testStatus = {};
            let flag = false;

            this.testDataList.forEach((online) => {
              if (real.user_id == online.studentId) {
                if (!online.result_list[index]) {
                  return;
                }
                testStatus = {
                  studentId: online.studentId,
                  studentName: online.studentName,
                  joinFlag: true,
                  answerSelection:
                    NumToEng[online.result_list[index].testSelection],
                  answerResult: online.result_list[index].answerResult,
                };
                join_student_count++;
                flag = true;
                studentAnswerList.push(testStatus);
              }
            });
            if (flag == false) {
              testStatus = {
                studentId: real.user_id,
                studentName: real.name,
                joinFlag: false,
                answerSelection: "",
                answerResult: false,
              };
              studentAnswerList.push(testStatus);
            }
          });
          //
          testAnswersData.push({
            studentAnswerList,
            question: {
              title: questionItem.content,
              options: questionItem.options,
              question_type: questionItem.type,
              right_answer: questionItem.right_answer,
            },
          });
        });
      });

      let testData = {
        total_number: this.realStudents.length,
        real_number: join_student_count,
        class_name: this.curclassName,
        class_id: this.curclassId,
        record: testAnswersData,
      };
      this.testDataArray.push(testData);
    },
    saveFileData() {
      let fileAnswersData = [];
      //**************保存随堂测试数据

      let join_student_count = 0;
      this.realStudents.forEach((real) => {
        let fileStatus = {};
        let flag = false;

        this.fileDataList.forEach((online) => {
          if (real.user_id == online.studentId && online.role != "teacher") {
            fileStatus = {
              studentId: online.studentId,
              studentName: online.studentName,
              submitTime: online.submitTime,
              joinFlag: true,
              phaseIndex: online.phaseIndex,
              result_list: online.result_list,
            };
            join_student_count++;
            flag = true;
            fileAnswersData.push(fileStatus);
          }
        });
        if (flag == false) {
          fileStatus = {
            studentId: real.user_id,
            studentName: real.name,
            submitTime: "",
            joinFlag: false,
            phaseIndex: "",
            result_list: "",
          };
          fileAnswersData.push(fileStatus);
        }
      });

      // fileAnswersData=this
      let fileData = {
        total_number: this.realStudents.length,
        real_number: join_student_count,
        class_name: this.curclassName,
        class_id: this.curclassId,
        file_list: fileAnswersData,
      };
      this.testDataArray.push(fileData);
    },
  },
};
</script>

<style scoped>
.active{
   color: #66afe9;
}

.interaction {
  display: flex;
  justify-content: space-around;
}
.onlineInfo {
  width: 25%;
  border: 1px solid black;
  margin-bottom: -1px ;
  /* padding: 10px; */
}
.onlineInfo .onlineInfo-header {
  display: flex;
  position: relative;
  height: 46px;
  width: 100%;
  background: #f4f4f4;
  color: #222;
  border-radius: 2px;
  box-sizing: border-box;
  cursor: pointer;
}
.onlineInfo .onlineInfo-body {
  box-sizing: border-box;
  overflow: hidden;
  margin: 0 5px;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-title {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  position: relative;
  padding: 8px 0;
  overflow: hidden;
  z-index: 1;
  zoom: 1;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-title .onlineInfo-body-left {
  padding-left: 8px;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-list {
  background-color: #fff;
  position: relative;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-list ul {
  list-style: none;
  outline: none;
  padding-left: 0;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-list ul li {
  font-size: 12px;
  color: #6d757a;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: space-between;
}

.onlineInfo .onlineInfo-body .onlineInfo-body-list .onlineInfo-body-li-name {
  width: 60px;
  position: relative;
  overflow: hidden;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-list .onlineInfo-body-li-time {
  width: 88px;
  color: #222;
  position: relative;
  overflow: hidden;
}
.onlineInfo .onlineInfo-body .onlineInfo-body-list .onlineInfo-body-li-flag {
  width: 60px;
  position: relative;
  overflow: hidden;
}

.onlineInfo .onlineInfo-header .onlineInfo-arrow {
  height: 14px;
  position: absolute;
  right: 14px;
  top: 0;
  bottom: 0;
  margin: auto;
  color: #505050;
}
.onlineInfo .onlineInfo-header .onlineInfo-filter {
  display: flex;
  position: relative;
  box-sizing: border-box;
  z-index: 2;
  height: 46px;
  line-height: 46px;
  border: none;
  border-radius: 2px;
  padding: 0 10px 0 16px;
  zoom: 1;
}
.onlineInfo .onlineInfo-header .onlineInfo-filter:hover{
  color: #66afe9;;
  font-weight: bold;
}
.onlineInfo .onlineInfo-header .onlineInfo-filter:active{
  top:2px;
}
/* h3,
ul li {
  color: #fff;
} */
.live {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
.live .live-header h2 {
  color: #1890ff;
  text-align: center;
  margin-right: 1.5rem;
  font-weight: bold;
}
.onlineInfo .onlineInfo-header .onlineInfo-chating {
  display: flex;
  position: relative;
  box-sizing: border-box;
  z-index: 2;
  height: 46px;
  line-height: 46px;
  border: none;
  border-radius: 2px;
  padding: 0 10px 0 16px;
  zoom: 1;
  cursor: hand;
}
.onlineInfo .onlineInfo-header .onlineInfo-chating:hover{
  color: #66afe9;
  font-weight: bold;
}
.onlineInfo .onlineInfo-header .onlineInfo-chating:active{
  top: 2px;
}
.onlineInfo .onlineInfo-header .onlineInfo-chating:visited{
  background-color: rgb(0, 0, 2);
}

/* 聊天框样式 */
.contentlabel{
  font-weight: bold;
  display: flex;
  font-size:bold;
  justify-content: space-between;
  background-color: #fff;
  position: relative;
  padding: 8px 5px;
  overflow: hidden;
  z-index: 1;
  zoom: 1;
}

.chating{
  position: relative;
  bottom: 0;
  padding: 8px; 
}
.chating input{
  width: 200px;
  height: 30px;
  border:2px solid grey;
  border-radius:25px;
 }
.chating input:focus{
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.281),0 0 8px rgba(102,175,233,.6);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.281),0 0 8px rgba(102,175,233,.6)
 }

.chating button{
  display:inline-block;
  padding:6px 13px;
  font-size:5px;
  cursor:pointer;
  text-align:center;
  text-decoration:none;
  outline:none;
  color:#fff;
  background-color:#66afe9;
  border:none;
  border-radius:10px;
  box-shadow: 5px 5px 2px grey;
  }
  .chating button:hover{
    background-color:#46a6e6
  }
  .chating button:active{
    background-color: #46a6e6;
    box-shadow:0 5px grey;
    transform:translateY(4px)
  }
  .chatRoom{
  overflow-y:scroll; 
  overflow-x:hidden;
  height: 350px;
  padding: 8px;
 }
 .chatContent{
  display:flex;
  height:auto;
  word-break:break-all;
 }
/* 聊天框样式结束 */

/* .chating{
  position: relative;
  top: 1000px; 
  bottom: 0;
  display: flex;
  padding: 8px;
}
.input{
  width: 268px;
  height: 30px;
  border: 0;
  outline: 0;
   border: solid 1px black; 
  background-color: rgb(234, 241, 245);
  margin: 0px -1px -1px 0px;
} */
/* .input:focus{
  outline:  1.5px solid rgb(143, 171, 180);
}
.btn{
  color: rgb(248, 239, 239);
  position: relative;
  box-sizing: border-box;
  z-index: 2;
  height: 30px;
  border: 1px solid rgb(10, 10, 10);
  border-radius: 2px;
  padding: 0 10px 0 16px;
  background-color: #1890ff;
}
.btn:active{
  outline: red;
  top:2px;
} */
.father{
  position: relative;
  width:630px;
  height:400px;
}
#videoElement {
  /* 屏幕宽度，在这改 */
  --width: 630px;
  --height: 400px;
  width: var(--width);
  height: var(--height);
  position:relative;
  z-index:-1;
}
.little-redpoint{
   background: red;
   border-radius:50px;/*设置圆角*/
   position: absolute;
   left:5px;
   top:5px; 
   width: 10px;
   height: 10px;  
}

@keyframes scale{
     /* 0%{transform:scale(1)}
     50%,75%{transform:scale(2)}
     78%,100%{opacity:0} */
        0% {
      transform: scale(0.5);
      opacity: 1;
    }
 
    30% {
      opacity: 1;
    }
 
    100% {
      transform: scale(2);
      opacity: 0;
    }
}

.little-redpoint::before{
  content: '';
  display:block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #FF0033;
  opacity: 0.9;
  animation: scale 1s infinite cubic-bezier(0,0,.49,1.02);
  animation-delay: 300ms;
}
.little-redpoint-display{
  background: red;
   border-radius:50px;/*设置圆角*/
   position: absolute;
   left:5px;
   top:5px; 
   width: 10px;
   height: 10px;
}


.btn-area {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}
</style>
